<template>
    <div class="shop-page">
        <div class="shop-header">
            <div class="header-left">
                <img :src="shopInfo.logo || defaultLogo" class="shop-logo" />
                <div class="shop-meta">
                    <div class="shop-name">{{ shopInfo.shopName || "未知店铺" }}</div>
                    <div class="stats">
                        <span>粉丝数：{{ shopInfo.fanCount || 0 }}</span>
                        <span>评分：{{ shopInfo.shopScore || "暂无评分" }}</span>
                        <span>开店时间：{{ formatTime(shopInfo.createTime) || "未知" }}</span>
                    </div>
                </div>
            </div>
            <div class="header-right">
                <el-button
                    :type="isCollected ? 'default' : 'primary'"
                    :icon="isCollected ? 'el-icon-star-off' : 'el-icon-star-on'"
                    :loading="collecting"
                    @click="toggleCollect"
                >
                    {{ isCollected ? '已收藏' : '收藏' }}
                </el-button>
                <el-button icon="el-icon-service"  @click="router.push(`/shopChat/${route.params.id}`)">客服</el-button>
            </div>
        </div>

        <el-row :gutter="20" class="main-layout">
            <el-col :span="5">
                <div class="category-panel">
                    <button class="category-title" @click="handleAllProducts">全部宝贝</button>
                    <el-menu
                        v-model="currentMenuIndex"
                        class="category-menu"
                        @select="handleCategorySelect"
                    >
                        <template v-if="categoryList.length">
                            <el-menu-item
                                v-for="(category, idx) in categoryList"
                                :key="idx"
                                :index="(idx + 1).toString()"
                            >
                                {{ category }}
                            </el-menu-item>
                        </template>
                        <template v-else>
                            <div class="empty-tip">暂无商品分类</div>
                        </template>
                    </el-menu>
                </div>
            </el-col>

            <el-col :span="19">
                <div class="filter-bar">
                    <el-radio-group v-model="activeFilter" @change="handleFilterChange">
                        <el-radio label="销量">销量</el-radio>
                        <el-radio label="新品">新品</el-radio>
                        <el-radio label="价格">价格</el-radio>
                    </el-radio-group>
                </div>

                <el-skeleton v-if="loading" :count="8" class="skeleton-loading" />
                <div v-else-if="shopData.length === 0" class="empty-state">
                    <el-empty description="暂无商品数据"></el-empty>
                </div>
                <el-row :gutter="16" v-else>
                    <el-col :span="6" v-for="(prod, idx) in filteredProducts" :key="prod.productId || idx">
                        <el-card class="product-card" @click="router.push('/productMain/'+prod.productId)">
                            <template #cover>
                                <el-image
                                    :src="prod.mainImg || defaultProductImg"
                                    fit="cover"
                                    class="product-img"
                                    :alt="prod.name"
                                />
                            </template>
                            <div class="product-info">
                                <div class="prod-name">{{ prod.name || "未知商品" }}</div>
                                <div class="price-row">
                                    <span class="price">¥{{ prod.priceBefore || 0 }}</span>
                                    <span class="sales">{{ prod.orderCount || 0 }}人付款</span>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import axios from "axios";
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus';
const router = useRouter();
const route = useRoute();

const defaultLogo = "https://picsum.photos/60/60?random=1";
const defaultProductImg = "https://picsum.photos/200/200?random=2";



const shopData = ref<any[]>([]);
const categoryList = ref<string[]>([]);
const activeFilter = ref('销量');
const activeCategory = ref('');
const loading = ref(true);
const shopInfo = ref<any>({});
const currentMenuIndex = ref('');

const isCollected = ref(false);
const collecting = ref(false);

const formatTime = (timeStr: string) => {
    if (!timeStr) return '';
    return new Date(timeStr).toLocaleDateString();
};

const filteredProducts = computed(() => {
    let result = [...shopData.value];
    if (activeCategory.value) {
        result = result.filter(prod => prod.type === activeCategory.value);
    }
    switch (activeFilter.value) {
        case '销量':
            return result.sort((a, b) => (b.orderCount || 0) - (a.orderCount || 0));
        case '新品':
            return result.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime());
        case '价格':
            return result.sort((a, b) => (a.priceBefore || 0) - (b.priceBefore || 0));
        default:
            return result;
    }
});

const handleCategorySelect = (index: string) => {
    const idx = parseInt(index) - 1;
    activeCategory.value = categoryList.value[idx] || '';
    currentMenuIndex.value = index;
};

const handleAllProducts = () => {
    activeCategory.value = '';
    currentMenuIndex.value = '';
};

const handleFilterChange = () => {};

const doList = async () => {
    try {
        loading.value = true;
        const shopId = route.params.id;
        if (!shopId) {
            console.error("未获取到店铺ID");
            return;
        }
        const { data } = await axios.get('/api/shop/products', { params: { shopId } });
        shopData.value = data || [];
        if (shopData.value.length > 0) {
            shopInfo.value = {
                shopName: shopData.value[0].shopName,
                fanCount: shopData.value[0].fanCount,
                shopScore: shopData.value[0].shopScore,
                createTime: shopData.value[0].createTime,
                logo: shopData.value[0].logo
            };
        }
        const typeSet = new Set<string>();
        shopData.value.forEach(prod => {
            if (prod.type && typeof prod.type === 'string') {
                typeSet.add(prod.type.trim());
            }
        });
        categoryList.value = Array.from(typeSet);
    } catch (error) {
        console.error("获取商品数据失败：", error);
        shopData.value = [];
    } finally {
        loading.value = false;
    }
};

const checkIsCollected = async () => {
    const shopId = route.params.id;
    const userId = 1; // 硬编码默认用户ID为1
    if (!userId || !shopId) return;
    try {
        const { data } = await axios.get('/api/shop/collect/isCollected', { params: { userId, shopId } });
        isCollected.value = data === 1;
    } catch (error) {
        console.error('查询收藏状态失败', error);
    }
};

const refreshFanCount = async () => {
    const shopId = route.params.id;
    try {
        const { data } = await axios.get('/api/shop/collect/count', { params: { shopId } });
        shopInfo.value.fanCount = data;
    } catch (error) {
        console.error('获取粉丝数失败', error);
    }
};

const toggleCollect = async () => {
    const shopId = route.params.id;
    const userId = 1; // 硬编码默认用户ID为1
    if (!shopId) {
        ElMessage.error('店铺信息错误');
        return;
    }
    if (collecting.value) return;
    collecting.value = true;
    try {
        if (isCollected.value) {
            await axios.delete('/api/shop/collect/deleteByUserAndShop', { params: { userId, shopId } });
            ElMessage.success('已取消收藏');
        } else {
            await axios.post('/api/shop/collect/insert', null, { params: { userId, shopId } });
            ElMessage.success('收藏成功');
        }
        isCollected.value = !isCollected.value;
        await refreshFanCount();
    } catch (error) {
        console.error('收藏操作失败', error);
        ElMessage.error(isCollected.value ? '取消收藏失败' : '收藏失败');
    } finally {
        collecting.value = false;
    }
};

onMounted(async () => {
    await doList();
    await checkIsCollected();
});
</script>

<style scoped>
.shop-page {
    padding: 20px;
    background: #fff;
    min-height: calc(100vh - 64px);
}
.shop-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: #fcfcfc;
    border-radius: 8px;
    margin-bottom: 20px;
    height: 80px;
    position: sticky;
    top: 0;
    z-index: 10;
    border-bottom: 1px solid #eee;
}
.header-left {
    display: flex;
    align-items: center;
}
.shop-logo {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-right: 12px;
    object-fit: cover;
}
.shop-meta {
    display: flex;
    flex-direction: column;
}
.shop-name {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}
.stats {
    margin-top: 4px;
    font-size: 14px;
    color: #666;
}
.stats span {
    margin-right: 15px;
}
.header-right {
    display: flex;
    gap: 8px;
}
.main-layout {
    background: #f8f8f8;
    border-radius: 8px;
    padding: 20px;
    margin-top: 20px;
    overflow: visible;
}
.category-panel {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    position: sticky;
    top: 100px;
    align-self: flex-start;
}
.category-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
    background: none;
    border: none;
    width: 100%;
    text-align: left;
    cursor: pointer;
    color: #333;
}
.category-title:hover {
    color: #1890ff;
}
.category-menu {
    border: none;
}
.empty-tip {
    padding: 16px;
    text-align: center;
    color: #999;
}
.filter-bar {
    background: #fff;
    padding: 12px 16px;
    margin-bottom: 16px;
    border-radius: 8px;
}
.product-card {
    height: 300px;
    display: flex;
    flex-direction: column;
    border-radius: 8px;
    overflow: hidden;
    transition: transform 0.2s;
}
.product-card:hover {
    transform: translateY(-4px);
}
.product-img {
    width: 100%;
    height: 180px;
    object-fit: cover;
}
.product-info {
    padding: 12px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
}
.prod-name {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
.price-row {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
}
.price {
    font-size: 16px;
    color: #ff4d4f;
    font-weight: 600;
}
.sales {
    font-size: 12px;
    color: #999;
}
.skeleton-loading {
    padding: 16px 0;
}
.empty-state {
    padding: 40px 0;
    text-align: center;
}
</style>